<template>
  <div class="login-container">
    <!-- 头部 -->
    <van-nav-bar title="黑马头条登录">
    </van-nav-bar>
    <!-- 表单 -->
    <van-form @submit="onSubmitFn">
      <van-field
        v-model="formLogin.mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="rules.tel"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="rules.password"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          :loading="isLoading"
          type="info"
          native-type="submit"
          loading-text="加载中..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Notify } from 'vant'
import { mapActions } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      // 校验规则
      rules: {
        tel: [
          {
            required: true,
            message: '请填写手机号',
            trigger: 'onChange'
          },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请填写正确的手机号',
            trigger: 'onChange'
          }
        ],
        password: [
          {
            required: true,
            message: '请填写密码',
            trigger: 'onChange'
          },
          {
            pattern: /^\d{6}$/,
            message: '请填写正确的密码',
            trigger: 'onChange'
          }
        ]
      },
      // 登录表单数据
      formLogin: {
        // 手机号
        mobile: '13888886666',
        // 密码
        code: '246810'
      },
      // 加载状态
      isLoading: false
    }
  },
  methods: {
    ...mapActions(['asyncLoginAction']),
    // 登录按钮的 提交事件 - 只有通过校验才会执行这个函数
    async onSubmitFn () {
      this.isLoading = true
      // 把用户输入的手机号与密码发送给后台
      try {
        await this.asyncLoginAction({
          tel: this.formLogin.mobile,
          pwd: this.formLogin.code
        })
        Notify({ type: 'success', message: '登录成功' })
        // 登陆成功后直接跳转到Layout页面
        this.$router.replace({
          path: this.$route.query.from || '/layout'
        })
      } catch (err) {
        Notify({ type: 'danger', message: '手机号或密码错误' })
      } finally {
        // 不管登录是否成功，都要将按钮解禁
        this.isLoading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
// .van-nav-bar {
//   background: #007bff;
//   // /deep/ 就是把data-v-hash值选择器写到类名的前面
//   /deep/ .van-nav-bar__title {
//     color: #fff;
//   }
// }
</style>
